using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace DareMusicFixer
{    
    public partial class TagDisplay : Form
    {
        #region Member Variables
        public event SaveHandler Saved;        
        DareMp3Tag mDTag;

        byte[] mImage;

        string mTitle = "Edit Dare MP3 Tag";
        #endregion

        #region Constructors
        public TagDisplay(DareMp3Tag dtag)            
        {
            InitializeComponent();
            mDTag = dtag;
            UpdateUI();
        }
        #endregion

        #region Properties
        public DareMp3Tag DTag
        {
            get { return mDTag; }
        }
        #endregion

        #region Event Handlers
        private void saveButton_Click(object sender, EventArgs e)
        {
            if (Saved != null)
            {
                Saved(this, new SaveEventArgs(mDTag));
            }

            DTag.ForceWrite = true;
            SaveDTag();
            DialogResult = DialogResult.OK;
            Close();
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }


        private void titleBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                saveButton_Click(this, null);
            }
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            AlbumArtGrabber grabber = new AlbumArtGrabber();
            if (grabber.GrabCover(artistBox.Text, albumBox.Text))
            {
                mImage = grabber.Image;
                ShowScaledImage();
            }
            else
            {
                MessageBox.Show("Album not found on Amazon, check spelling or drag and drop the cover art.", "Art Not Found");
            }
        }

        private void TagDisplay_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

            byte[] buffer = new byte[4096];

            using (FileStream fs = File.Open(files[0], FileMode.Open))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    int count = 0;
                    do
                    {
                        count = fs.Read(buffer, 0, buffer.Length);
                        memoryStream.Write(buffer, 0, count);

                    } while (count != 0);

                    mImage = memoryStream.ToArray();
                }
            }

            ShowScaledImage();
        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            mImage = null;
            ShowScaledImage();
        }

        private void TagDisplay_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }
        #endregion

        #region Public Helpers
        delegate void SetNumCompletedDelegate(int num, int total);
        public void SetNumCompleted(int num, int total)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new SetNumCompletedDelegate(SetNumCompleted), new object[] { num, total });
            }
            else
            {
                this.Text = num + "/" + total + " " + mTitle;
            }
        }
        #endregion

        #region Private Helpers
        private void UpdateUI()
        {
            filenameBox.Text = mDTag.Filename;
            albumBox.Text = mDTag.Album;
            artistBox.Text = mDTag.Artist;
            titleBox.Text = mDTag.Title;
            trackNumBox.Text = mDTag.Track.ToString();
            mImage = mDTag.Image;
            ShowScaledImage();
        }

        private void SaveDTag()
        {
            mDTag.Filename = filenameBox.Text;
            mDTag.Album = albumBox.Text;
            mDTag.Artist = artistBox.Text;
            mDTag.Title = titleBox.Text;
            try
            {
                mDTag.Track = uint.Parse(trackNumBox.Text);
            }
            catch (FormatException)
            {
                mDTag.Track = 0;
            }
            if (forceResize.Checked)
            {
                Image img = ImageHelpers.ByteArrayToImage(mImage);
                if (img.Width != 200 && img.Height != 200)
                {
                    mImage = ImageHelpers.Scale(img, 200, 200);
                }
            }
            mDTag.Image = mImage;
        }

        private void ShowScaledImage()
        {
            if (mImage != null && mImage.Length > 0)
            {
                // resize the image so that it fits in the box
                byte[] scaledImage = ImageHelpers.Scale(
                    ImageHelpers.ByteArrayToImage(mImage),
                    pictureBox1.Width,
                    pictureBox1.Height
                    );

                pictureBox1.Image = ImageHelpers.ByteArrayToImage(scaledImage);
            }
            else
            {
                pictureBox1.Image = null;
            }
        }
        #endregion
    }

    #region SaveEventArgs
    public delegate void SaveHandler(object sender, SaveEventArgs e);
    public class SaveEventArgs : EventArgs
    {
        public SaveEventArgs() { }

        public SaveEventArgs(DareMp3Tag dtag)
        {
            mDTag = dtag;
        }

        public DareMp3Tag DTag
        {
            get { return mDTag; }
        }

        DareMp3Tag mDTag;
    }
    #endregion
}